﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace FriendService
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        LifeShareUserEntities myFriendSystem = new LifeShareUserEntities();

        private void AddNewsToFriends(UserData currentUser, PublishItem newsItem)
        {
            int iMax1 = 0;
            if (myFriendSystem.News.Count() > 0)
                iMax1 = myFriendSystem.News.Max(news => news.NewsID);

            var queryFriendRelation = from relation in myFriendSystem.FriendRelation
                                      where relation.UserTo.UserID == currentUser.UserID
                                      select new { id = relation.UserFrom.UserID };

            foreach (var relation in queryFriendRelation)
            {
                News newNews = new News
                {
                    NewsID = ++iMax1,
                    UserData = GetUserById(relation.id),
                    PublishItem = newsItem
                };

                myFriendSystem.AddToNews(newNews);
            }
        }

        private UserData GetUserById(int id)
        {
            var queryUser = from user in myFriendSystem.UserData
                            where user.UserID == id
                            select user;

            if (queryUser.Count() == 0)
                return null;

            return queryUser.First();
        }

        [WebMethod]
        public int Logon(string email, string pwd)
        {
            var query = from user in myFriendSystem.UserData
                        where user.UserEmail == email && user.UserPwd == pwd
                        select user;

            if (query.Count() > 0)
                return query.First().UserID;   
            return -1;
        }

        [WebMethod]
        public FriendModel.UserData GetUserData(int ID)
        {
            var query = from user in myFriendSystem.UserData
                        where user.UserID == ID
                        select user;

            UserData d = query.First();

            FriendModel.UserData data = new FriendModel.UserData
            {
                id = ID,
                userName = d.UserName,
                userEmail = d.UserEmail,
                userSex = (int)d.UserSex,
                registerDate = (DateTime)d.RegisterDate
            };

            return data;
        }

        [WebMethod]
        public int RegistereUser(string Email, string Name, string Pwd, int gender)
        {
            var queryEmail = from user in myFriendSystem.UserData
                             where user.UserEmail == Email
                             select user;
            if (queryEmail.Count() > 0)
                return -1;
            
            int Max = myFriendSystem.UserData.Max(user => user.UserID);


            UserData newData = new UserData
            {
                UserID = Max + 1,
                UserEmail = Email,
                UserName = Name,
                UserPwd = Pwd,
                UserSex = gender,
                RegisterDate = DateTime.Today.Date + DateTime.Today.Date.TimeOfDay
            };

            myFriendSystem.AddToUserData(newData);
            if(myFriendSystem.SaveChanges(false) == 0)
                return -1; 
            return newData.UserID;
        }

        [WebMethod]
        public bool PublishAStatus(int userId, string strContent)
        {
            int iMax;
            if (myFriendSystem.PublishItem.Count() > 0)
                iMax = myFriendSystem.PublishItem.Max(maxItem => maxItem.PublishID);
            else
                iMax = 0;

            var queryUser = from user in myFriendSystem.UserData
                            where user.UserID == userId
                            select user;

            UserData currentUser = queryUser.First();

            PublishItem newItem = new PublishItem
            {
                PublishID = iMax + 1,
                PublishDate = DateTime.Now.Date + DateTime.Now.TimeOfDay,
                PublishType = 0
            };

            currentUser.PublishItem.Add(newItem);

            newItem.PublishStatus = new PublishStatus
            {
                PublishItem = newItem,
                StatusContent = strContent
            };

            AddNewsToFriends(currentUser, newItem);
            if(myFriendSystem.SaveChanges(false) == 0)
                return false;
            return true;
        }

        [WebMethod]
        public bool PublishAShare(int userId, int resourceId)
        {
            int iMax;
            if (myFriendSystem.PublishItem.Count() > 0)
                iMax = myFriendSystem.PublishItem.Max(maxItem => maxItem.PublishID);
            else
                iMax = 0;

            var queryUser = from user in myFriendSystem.UserData
                            where user.UserID == userId
                            select user;

            if(queryUser.Count() == 0)
                return false;

            UserData currentUser = queryUser.First();

            PublishItem newItem = new PublishItem
            {
                PublishID = iMax + 1,
                PublishDate = DateTime.Now.Date + DateTime.Now.TimeOfDay,
                PublishType = 1
            };

            currentUser.PublishItem.Add(newItem);

            newItem.PublishShare = new PublishShare
            {
                PublishItem = newItem,
                ResourceID = resourceId
            };

            AddNewsToFriends(currentUser, newItem);
            if (myFriendSystem.SaveChanges(false) == 0)
                return false;
            return true;
        }

        [WebMethod]
        public string AddFriend(int userId, int friendId)
        {
            if (IsFriend(userId, friendId))
                return "aleardy friend";
            var queryUser = from user in myFriendSystem.UserData
                            where user.UserID == userId
                            select user;

            if (queryUser.Count() == 0)
                return "user： " + userId + " not found!";

            var queryFriend = from user in myFriendSystem.UserData
                              where user.UserID == friendId
                              select user;

            if (queryFriend.Count() == 0)
                return "friend: " + friendId + " not found!";

            UserData currentUser = queryUser.First();
            UserData friendUser = queryFriend.First();
           
            int iMax = 0;
            if( myFriendSystem.FriendRelation.Count() > 0)
                iMax = myFriendSystem.FriendRelation.Max(relation => relation.FriendID);

            currentUser.FriendFrom.Add(new FriendRelation
                {
                    FriendID = iMax + 1,
                    UserFrom = currentUser,
                    UserTo = friendUser,
                    FriendDate = DateTime.Now.Date + DateTime.Now.TimeOfDay
                });

            if (myFriendSystem.SaveChanges(false) == 0)
                return "add friend failed!";

            return "add friend: " + friendUser.UserName + " successfully!";
        }

        [WebMethod]
        public int AddCommentToItem(int itemId, string strComment, int fromId, int toId)
        {
            var queryItem = from item in myFriendSystem.PublishItem
                            where item.PublishID == itemId
                            select item;
            PublishItem selectedItem = queryItem.First();

            int iMaxId = 0;
            if( myFriendSystem.Comment.Count() > 0)
                iMaxId = myFriendSystem.Comment.Max(comment=>comment.CommentID);

            UserData userFrom = GetUserById(fromId);
            UserData userTo = GetUserById(toId);

            selectedItem.Comment.Add(new Comment
            {
                CommentID = iMaxId + 1,
                CommentDate = DateTime.Now.Date + DateTime.Now.TimeOfDay,
                CommentContent = strComment,
                UserFrom = userFrom,
                UserTo = userTo
            });

            if (myFriendSystem.SaveChanges(false) == 0)
                return -1;
            return iMaxId + 1;
        }

        [WebMethod]
        public List<FriendModel.PublishStatus> GetStatusByUserId(int id)
        {
            List<FriendModel.PublishStatus> AllStatus = new List<FriendModel.PublishStatus>();
           
            var queryStatus = from status in myFriendSystem.PublishStatus
                              where status.PublishItem.UserData.UserID == id
                              select new
                              {
                                  id = status.PublishID,
                                  date = status.PublishItem.PublishDate,
                                  content = status.StatusContent,
                                  userid = status.PublishItem.UserData.UserID
                              };
           
            foreach (var status in queryStatus)
            {
                FriendModel.PublishStatus myStatus = new FriendModel.PublishStatus
                {
                    id = status.id,
                    publishDate = status.date,
                    statusContent = status.content,
                    userId = status.userid
                };

                AllStatus.Add(myStatus);
            }
           return AllStatus; 
       }

        [WebMethod]
        public FriendModel.PublishShare GetShareByItemId(int itemId)
        {
            List<FriendModel.PublishShare> allShare = new List<FriendModel.PublishShare>();

            var queryShare = from share in myFriendSystem.PublishShare
                             where share.PublishID == itemId
                             select new{
                                userId = share.PublishItem.UserData.UserID,
                                resourceId = share.ResourceID,
                                id = itemId,
                                type = share.PublishItem.PublishType,
                                date = share.PublishItem.PublishDate
                                };
            if( queryShare.Count()==0)
                return null;
            var shareResult = queryShare.First();

            FriendModel.PublishShare selectedShare = new FriendModel.PublishShare
            {
                userId = shareResult.userId,
                id = shareResult.id,
                publishDate = shareResult.date,
                type = (int)shareResult.type,
                resourceId = (int)shareResult.resourceId

            };

            return selectedShare;
        }

        [WebMethod]
        public List<FriendModel.News> GetNewsList(int userId)
        {
            List<FriendModel.News> newsList = new List<FriendModel.News>();

            var queryUser = from user in myFriendSystem.UserData
                            where user.UserID == userId
                            select user;
            if (queryUser.Count() == 0)
                return newsList;
            UserData currentUser = queryUser.First();

            var queryNews = from news in myFriendSystem.News
                            where news.UserData.UserID == userId
                            select new { id = news.NewsID,
                                         userid = news.UserData.UserID,
                                         publishId = news.PublishItem.PublishID    
                                        };


            foreach (var news in queryNews)
            {
                FriendModel.News myNews = new FriendModel.News
                {
                    id = news.id,
                    newsOwnerId = news.userid,
                    newsPublishItemId = news.publishId
                };

                newsList.Add(myNews);
            }
            return newsList;
        }

        [WebMethod]
        public FriendModel.News GetNewsById(int newsId)
        {
            var queryNews = from news in myFriendSystem.News
                            where news.NewsID == newsId
                            select new
                            {
                                id = news.NewsID,
                                ownerid = news.UserData.UserID,
                                itemid = news.PublishItem.PublishID
                            };

            if (queryNews.Count() == 0)
                return null;

            var selectedNews = queryNews.First();

            FriendModel.News newNews = new FriendModel.News
            {
                id = selectedNews.id,
                newsOwnerId = selectedNews.ownerid,
                newsPublishItemId = selectedNews.itemid
            };

            return newNews;
        }

        [WebMethod]
        public bool DeleteNewsById(int newsId)
        {
            var queryNews = from news in myFriendSystem.News
                            where news.NewsID == newsId
                            select news;

            if (queryNews.Count() == 0)
                return false;

            News selectedNews = queryNews.First();

            myFriendSystem.DeleteObject(selectedNews);
            myFriendSystem.SaveChanges();
            return true;
        }

        [WebMethod]
        public List<FriendModel.UserData> GetFriendList(int userId)
        {
            UserData currentUser = GetUserById(userId);
            List<FriendModel.UserData> friendList = new List<FriendModel.UserData>();

            var queryFriend = from relation in myFriendSystem.FriendRelation
                              where relation.UserFrom.UserID == currentUser.UserID
                              select new {id = relation.UserTo.UserID,
                                        name = relation.UserTo.UserName,
                                        email = relation.UserTo.UserEmail,
                                        sex = relation.UserTo.UserSex,
                                        registerdate = relation.UserTo.RegisterDate
                              };

            foreach (var friend in queryFriend)
            {
                FriendModel.UserData friendData = new FriendModel.UserData
                {
                    id = friend.id,
                    userName = friend.name,
                    userEmail = friend.email,
                    userSex = (int)friend.sex,
                    registerDate = (DateTime)friend.registerdate
                };
                friendList.Add(friendData);
            }
            
            return friendList;
        }

        [WebMethod]
        public string[] GetFriendRelation()
        {
            List<string> result = new List<string>();

            var queryRelation = from relation in myFriendSystem.FriendRelation
                                select new {
                                    userfrom = relation.UserFrom.UserName,
                                    userto = relation.UserTo.UserName
                                };
                              

            foreach (var relation in queryRelation)
            {
                result.Add("from: " + relation.userfrom + " to: " + relation.userto);
            }

            return result.ToArray();
        }

        [WebMethod]
        public bool IsFriend(int userId, int friendId)
        {
            var queryRelation = from relation in myFriendSystem.FriendRelation
                                where relation.UserFrom.UserID == userId && relation.UserTo.UserID == friendId
                                select relation;
            if (queryRelation.Count() == 0)
                return false;
            return true;
        }

        [WebMethod]
        public bool DeleteFriend(int userId, int friendId)
        {
            var queryRelation = from relation in myFriendSystem.FriendRelation
                                where relation.UserFrom.UserID == userId && relation.UserTo.UserID == friendId
                                select relation;
            if (queryRelation.Count() == 0)
                return false;
            myFriendSystem.DeleteObject(queryRelation.First());
            if (myFriendSystem.SaveChanges() == 0)
            {
                return false;
            }
            return true;
        }

        [WebMethod]
        public List<FriendModel.Comment> GetCommentList(int itemId)
        {
            List<FriendModel.Comment> commentList = new List<FriendModel.Comment>();

            var queryItem = from item in myFriendSystem.PublishItem
                            where item.PublishID == itemId
                            select item;
            if (queryItem.Count() == 0)
                return commentList;

            PublishItem selectedItem = queryItem.First();

            var queryComment = from comment in myFriendSystem.Comment
                               where comment.PublishItem.PublishID == itemId
                               select new { 
                                        id = comment.CommentID,
                                        date = comment.CommentDate,
                                        userfrom = comment.UserFrom.UserID,
                                        userto = comment.UserTo.UserID,
                                        content = comment.CommentContent,
                                        publishid = comment.PublishItem.PublishID,
                                        };

            foreach (var comment in queryComment)
            {
                FriendModel.Comment com = new FriendModel.Comment
                {
                    id = comment.id,
                    publishItemId = comment.publishid,
                    commentDate = comment.date,
                    fromUserId = comment.userfrom,
                    toUserId = comment.userto,
                    commentContent = comment.content
                };
                commentList.Add(com);
            }

            return commentList;
        }

        [WebMethod]
        public FriendModel.PublishItem GetPublishItemByPublishId(int itemId)
        {
            var queryPublishItem = from item in myFriendSystem.PublishItem
                                   where item.PublishID == itemId
                                   select new{
                                        id = item.PublishID,
                                        userid = item.UserData.UserID,
                                        publishdate = item.PublishDate,
                                        publishtype = item.PublishType
                                   };

            if (queryPublishItem.Count() == 0)
                return null;

            var selectedItem = queryPublishItem.First();

            FriendModel.PublishItem publishItem = new FriendModel.PublishItem
            {
                id = selectedItem.id,
                userId = selectedItem.userid,
                publishDate = selectedItem.publishdate,
                type = (int)selectedItem.publishtype
            };

            return publishItem;
        }

        [WebMethod]
        public List<FriendModel.PublishItem> GetPublishItemByUserId(int userId)
        {
            List<FriendModel.PublishItem> AllItem = new List<FriendModel.PublishItem>();

            var queryItem = from item in myFriendSystem.PublishItem
                            where item.UserData.UserID == userId
                            select item;

            foreach (var item in queryItem)
            {
                FriendModel.PublishItem selectedItem = new FriendModel.PublishItem
                {
                    userId = userId,
                    id = item.PublishID,
                    publishDate = item.PublishDate,
                    type = (int)item.PublishType
                };
                AllItem.Add(selectedItem);
            }
            return AllItem;
        }

        [WebMethod]
        public bool DeletePublishItemById(int itemId)
        {
            var queryItem = from item in myFriendSystem.PublishItem
                            where item.PublishID == itemId
                            select item;

            if (queryItem.Count() == 0)
                return false;

            PublishItem selectedItem = queryItem.First();
            if (selectedItem.PublishType == 0)
            {
                var queryStatus = from status in myFriendSystem.PublishStatus
                                  where status.PublishID == selectedItem.PublishID
                                  select status;
                if( queryStatus.Count() != 0)
                    myFriendSystem.DeleteObject(queryStatus.First());
            }
            else if (selectedItem.PublishType == 1)
            {
                var queryShare = from share in myFriendSystem.PublishShare
                                 where share.PublishID == selectedItem.PublishID
                                 select share;
                if( queryShare.Count() != 0)
                    myFriendSystem.DeleteObject(queryShare.First());
            }
            myFriendSystem.DeleteObject(selectedItem);
            myFriendSystem.SaveChanges();
            return true;
        }

        [WebMethod]
        public FriendModel.PublishStatus GetStatusByPublishId(int itemId)
        {
            var queryStatus = from status in myFriendSystem.PublishStatus
                              where status.PublishID == itemId
                              select new{
                                    id = status.PublishID,
                                    content = status.StatusContent,
                                    userid = status.PublishItem.UserData.UserID,
                                    datetime = status.PublishItem.PublishDate
                                    };
            
            if( queryStatus.Count() == 0)
                return null;
           
            var selectedStatus = queryStatus.First();

            FriendModel.PublishStatus newStatus = new FriendModel.PublishStatus
            {
                id = selectedStatus.id,
                userId = selectedStatus.userid,
                statusContent = selectedStatus.content,
                publishDate = selectedStatus.datetime
            };
            return newStatus;
        }
    }
}